package cn.geapi.core.util.security;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.geapi.core.util.security.annotation.IDType;

public class HashIdContext {
	private static Map<String, IHashIdStrategy> instanceMap = new ConcurrentHashMap<String, IHashIdStrategy>();
	private static IHashIdStrategy hashIdStrategy;

	/**
	 * 根据id类型构建hashid算法对象
	 * 
	 * @param idType
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	public final static IHashIdStrategy getHashIdStrategy(final IDType idType)
			throws InstantiationException, IllegalAccessException,
			ClassNotFoundException {

		StringBuffer buffer = new StringBuffer("cn.geapi.core.util.security.impl.")
				.append(idType.value()).append("StrategyImpl");
		String instanceName = buffer.toString();
		hashIdStrategy = instanceMap.get(instanceName);
		if (null == hashIdStrategy) {
			hashIdStrategy = (IHashIdStrategy) Class.forName(instanceName)
					.newInstance();
		}
		return hashIdStrategy;
	}

	/**
	 * 加密
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public String encrypt(Long id) {
		return hashIdStrategy.encrypt(id);
	}

	/**
	 * 解密
	 * 
	 * @param encrytId
	 * @return
	 */
	public Long decrypt(String encrytId) {
		return hashIdStrategy.decrypt(encrytId);
	}

}
